from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
import django.utils.html
import json
from django.views.decorators.csrf import csrf_exempt
import urllib2

def index(request):
    return render_to_response('search/index.html',
        { },
        context_instance=RequestContext(request))

def update_source(source, good_urls, bad_urls):
    if u'query' in source:
        qsrc = source[u'query']
        if u'query_string' in qsrc:
            qstr = qsrc[u'query_string']
            urls = [
                u'http://na11.apachecon.com/talks/19391',
                u'http://hbase.apache.org/',
            ]
            good_urls = [ u' _uid:"%s"^0.0' % (x,) for x in good_urls ]
            qstr[u'query'] += ''.join(good_urls)
            bad_urls = [ u' _uid:"%s"^-1.0' % (x,) for x in bad_urls ]
            qstr[u'query'] += ''.join(bad_urls)
            print 'XXX', qstr[u'query']

@csrf_exempt
def query(request):
    text = ''

    if request.method == 'GET':
        qdict = request.GET
        source = qdict['source']
        source = json.loads(source)
        good_urls = [
            u'http://na11.apachecon.com/talks/19391',
            u'http://hbase.apache.org/',
        ]
        bad_urls = [
        ]
        update_source(source, good_urls, bad_urls)
        qdict = qdict.copy()
        qdict['source'] = json.dumps(source)
        url_options = qdict.urlencode()
        es_url = 'http://localhost:9200/_search?&' + url_options
        ureq = urllib2.Request(es_url)
        opener = urllib2.build_opener()
        f = opener.open(ureq)
        text = f.read()

    if request.method == 'POST':
        queryPost = request.POST
        queryGet = request.GET
        if 'back' in queryGet and 'page' in queryPost:
            page = queryPost['page']
            print "returned from ", page
        elif 'bookmark' in queryGet and 'page' in queryPost:
            page = queryPost['page']
            print "bookmarked ", page
        elif 'timeOnSE' in queryGet:
            time = int(queryGet['timeOnSE'])

    return HttpResponse(text)
